//
//  Tools.swift
//  TradingPlatform
//
//  Created by tam on 2017/8/8.
//  Copyright © 2017年 Wilkinson. All rights reserved.
//

import UIKit
import Foundation
import Alamofire
import ObjectMapper
import SVProgressHUD

class Tools: NSObject {

    //判断是否为邮箱
    class func validateEmail(email: String) -> Bool {
        let emailRegex = "[A-Z0-9a-z._% -] @[A-Za-z0-9.-] \\.[A-Za-z]{2,4}"
        let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailTest.evaluate(with: email)
    }
    
    //判断是否为电话号码
    class func validateMobile(mobile: String) -> Bool {
        //手机号以13,15,17,18开头，八个 \d 数字字符
        let phoneRegex = "^((13[0-9])|(15[012356789])|(17[0,0-9])|(18[0,0-9]))\\d{8}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluate(with: mobile)
    }
    
    //判断是否为密码
    class func validatePassword(password: String) -> Bool {
        let passwordRegex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$"
        let passwordTest = NSPredicate(format: "SELF MATCHES %@", passwordRegex)
        return passwordTest.evaluate(with: password)
    }
    
    //判断是否为6位数字
    class func validateAuthorCode(code: String) -> Bool {
        let passwordRegex = "^\\d{6}$"
        let passwordTest = NSPredicate(format: "SELF MATCHES %@", passwordRegex)
        return passwordTest.evaluate(with: code)
    }

    //图片data转化字符串
    class func getStringDataFromImage(image: UIImage)-> String {
        var data: NSData;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0)! as NSData;
        }
        else
        {
            data = UIImagePNGRepresentation(image)! as NSData;
        }
        let imageString: String =  data.base64EncodedString(options: .lineLength64Characters)
        return imageString;
    }
    
    //获取当前时间
    class func getCurrentTime()-> String {
        let data = NSDate()
        let timeFormat = DateFormatter()
        timeFormat.dateFormat = "yyyMMddHHmmss"
        let currentTime = timeFormat.string(from: data as Date) as String
        return currentTime;
    }
    
    //获取当前时间
    class func getCurrentTimeMillis()-> String {
        let now = NSDate()
        let timeFormat = DateFormatter()
        timeFormat.dateFormat = "yyyMMddHHmmss"
        let timeInterval = now.timeIntervalSince1970
        let timeStamp = Int(timeInterval)
        return String.init(timeStamp)
    }
    
   
    
    
    
    //创建二维码图片
    class func createQRForString(qrString: String?, qrImageName: String?) -> UIImage?{
        
        if let sureQRString = qrString{
            let stringData = sureQRString.data(using: String.Encoding.utf8, allowLossyConversion: false)
            //创建一个二维码的滤镜
            let qrFilter = CIFilter(name: "CIQRCodeGenerator")
            qrFilter?.setValue(stringData, forKey: "inputMessage")
            qrFilter?.setValue("H", forKey: "inputCorrectionLevel")
            let qrCIImage = qrFilter?.outputImage
            
            // 创建一个颜色滤镜,黑白色
            let colorFilter = CIFilter(name: "CIFalseColor")!
            colorFilter.setDefaults()
            colorFilter.setValue(qrCIImage, forKey: "inputImage")
            colorFilter.setValue(CIColor(red: 0, green: 0, blue: 0), forKey: "inputColor0")
            colorFilter.setValue(CIColor(red: 1, green: 1, blue: 1), forKey: "inputColor1")
            // 返回二维码image
            let codeImage = UIImage(ciImage: (colorFilter.outputImage!.applying(CGAffineTransform(scaleX: 5, y: 5))))
            
            // 中间一般放logo
            if let logoImage = qrImageName {
                if let iconImage = UIImage(named: logoImage) {
                    let rect = CGRect(x: 0, y: 0, width: codeImage.size.width, height: codeImage.size.height)
                    
                    UIGraphicsBeginImageContext(rect.size)
                    codeImage.draw(in: rect)
                    let avatarSize = CGSize(width: rect.size.width*0.25, height: rect.size.height*0.25)
                    
                    let x = (rect.width - avatarSize.width) * 0.5
                    let y = (rect.height - avatarSize.height) * 0.5
                    iconImage.draw(in: CGRect(x: x, y: y, width: avatarSize.width, height: avatarSize.height))
                    
                    let resultImage = UIGraphicsGetImageFromCurrentImageContext()
                    
                    UIGraphicsEndImageContext()
                    return resultImage
                }

            }
            
            return codeImage
        }
        return nil
    }
    
    class func DLog<T>(message: T, file: String = #file, method: String = #function, line: Int = #line) {
        #if DEBUG
            print("<\((file as NSString).lastPathComponent): \(line)>, \(method), \(message)")
        #endif
    }
    
    class func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
    
    class func switchToLoginViewController() {
        
        let loginvc = LoginViewController()
        let navi = TPNavigationController.init(rootViewController: loginvc)
        UIApplication.shared.keyWindow?.rootViewController = navi        
    }
    
    class func switchToWalletViewController() {
        
        let loginvc = WalletViewController()
        let navi = TPNavigationController.init(rootViewController: loginvc)
        UIApplication.shared.keyWindow?.rootViewController = navi
    }
    
    class func cacheLoginData(token: String) {
        
        UserDefaults.standard.setValue(token, forKey: "token")
        UserDefaults.standard.setValue(true, forKey: "hadLogin")
        UserDefaults.standard.synchronize()
        
    }
    
    class func removeCacheLoginData() {
        
        UserDefaults.standard.setValue("", forKey: "token")
        UserDefaults.standard.setValue(false, forKey: "hadLogin")
        UserDefaults.standard.synchronize()
        
    }
    
    /// 将字典保存成本地沙盒Documents目录下json文件
    ///
    /// - Parameters:
    ///   - jsonDict: 数据字典
    ///   - fileName: Json文件名称
    class func storeJsonInDocuments(jsonDict: Dictionary<String, Any>, fileName: String) {
        
        let documentPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentPath = documentPaths[0]
        
        do {
            //将json保存到本地
            let filePath:String = documentPath + "/" + fileName + ".json"
            let data : NSData! = try? JSONSerialization.data(withJSONObject: jsonDict, options: []) as NSData!
            data.write(toFile: filePath, atomically: true)
            
            let loaddata = NSData(contentsOfFile: filePath)
            if loaddata != nil {
                let jData = loaddata! as Data
                let decoded = try JSONSerialization.jsonObject(with: jData, options: [])
                print("保存成功 译码：",decoded)
            }
        } catch {
            print(error.localizedDescription)
        }
    }
    
    
    /// 读取沙盒Documents文件夹下所有json格式文件
    ///
    /// - Returns: 所有json文件名称数组
    class func getJsonFileArrayInDocuments() -> NSMutableArray {
        
        let documentPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentPath = documentPaths[0]
        let jsonFilePathArray = try? FileManager.default.subpathsOfDirectory(atPath: documentPath)
        let fileArray = NSMutableArray()
        
        if jsonFilePathArray != nil {
            for filePath in jsonFilePathArray! {
                let lastpath = filePath.components(separatedBy: "/").last
                if (lastpath?.contains(".json"))! {
                    fileArray.add(lastpath!)
                }
            }
        }
        return fileArray
    }
    
    /// 读取沙盒Documents文件夹下需要导入的json格式文件（剔除数据库中数据）
    ///
    /// - Returns: 所有json文件名称数组
    class func getImportJsonFileArrayInDocuments() -> NSMutableArray {
        
        let documentPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentPath = documentPaths[0]
        let jsonFilePathArray = try? FileManager.default.subpathsOfDirectory(atPath: documentPath)
        let fileArray = NSMutableArray()
        
        if jsonFilePathArray != nil {
            for filePath in jsonFilePathArray! {
                let lastpath = filePath.components(separatedBy: "/").last
                if (lastpath?.contains(".json"))! {
                    
                    var dbcontain = false
                    for item in SQLiteManager.shareInstance.getWalletArrayInDB() {
                        let walllet = item as! WalletAddress
                        let jsonaddress = lastpath?.components(separatedBy: ".")
                        let address = jsonaddress![0] as! String
                        if walllet.address == address {
                            dbcontain = true
                        }
                    }
                    
                    if !dbcontain {
                        fileArray.add(lastpath!)
                    }
                }
            }
            
            
        }
        return fileArray
    }
    
    
    /// 获取Document下json文件的json字符串
    ///
    /// - Parameter fileName: json文件名称，包含.json后缀
    /// - Returns: json文件内容，json字符串
    class func getJsonFileContentInDocuments(fileName: String) -> String {
        
        let documentPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentPath = documentPaths[0]
        let filePath:String = documentPath + "/" + fileName
        let loaddata = NSData(contentsOfFile: filePath)
        
        if loaddata != nil {
            let jData = loaddata! as Data
            let JSONString = NSString(data:jData,encoding: String.Encoding.utf8.rawValue)
            print("译码：",JSONString as Any)
            return JSONString! as String
        } else {
            return ""
        }
    }
    
    class func getDictionaryFromJson(jsonString:NSString) -> NSDictionary {
        
        let jsonData: Data = jsonString.data(using: String.Encoding.utf8.rawValue)!
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    }
    
    
    class func transferAnyToDecimalNumber(value: Any?) -> NSDecimalNumber {
        let transfomer = NSDecimalNumberTransform.init()
        if let number = transfomer.transformFromJSON(value) {
            return number
        } else {
            return NSDecimalNumber.init(value: 0.0)
        }
        
    }
    
    class func transferDecimalNumberToString(value: NSDecimalNumber?) -> String {
        //todo: fix 小数位
        let transfomer = NSDecimalNumberTransform.init()
        if let numberStr = transfomer.transformToJSON(value) {
            return numberStr
        } else {
            return "0.0000"
        }
    }
    
    class func transferNumberToDecimalNumberString(value: Any?) -> String {
        let transfomer = NSDecimalNumberTransform.init()
        if let numberDecimal = transfomer.transformFromJSON(value) {
            let transfomer = NSDecimalNumberTransform.init()
            if let numberStr = transfomer.transformToJSON(numberDecimal) {
                return numberStr
            } else {
                return "0.0000"
            }
        } else {
            return "0.0000"
        }
    }
    
    class func caculateDecimalMultiple(first: NSNumber?, second: NSNumber?) -> String {
        
        if first != nil && second != nil {
            let firstNumber = Tools.transferAnyToDecimalNumber(value: first)
            let secondNumber = Tools.transferAnyToDecimalNumber(value: second)
            
            let valueNumber =  firstNumber.multiplying(by: secondNumber)
            return Tools.transferDecimalNumberToString(value: valueNumber)
        } else {
            return "0.0000"
        }
    }
    
}
